package com.sky.service.impl;

import ch.qos.logback.classic.joran.action.ConsolePluginAction;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.BaseException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //对前端传过来的明文密码进行MD5加密处理
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    //新增员工
    @Override
    public void save(EmployeeDTO employeeDTO) {
        //1.将DTO对象转成实体对象-对象属性拷贝-对象拷贝工具类BeanUtils
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);

        //2.1补全基础属性-账号状态：1正常0锁定
        employee.setStatus(StatusConstant.ENABLE);

        //2.2补全基础属性-设置默认密码123456-加密后的密码
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));

        /*
        //2.3补全基础属性-设置当前记录的创建时间和修改时间---使用@AutoFill注解集成了
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        //2.4补全基础属性-设置当前记录创建人和修改人
        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateUser(BaseContext.getCurrentId());
        */

        //3.调用Mapper执行插入员工
        employeeMapper.insert(employee);
    }

    //员工分页查询
    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        //select * from employee where name = ? order by desc

        //1.开始分页查询--PageHelper
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());

        //2.调用Mapper执行分页查询-pageHelper固定的返回值Page<实体>
        Page<Employee> page = employeeMapper.pageQuery(employeePageQueryDTO);

        //3.获取pageSize里面的两个参数:total,records
        long total = page.getTotal();
        List<Employee> records = page.getResult();
        return new PageResult(total, records);
    }

    //启用、禁用员工账号
    @Override
    public void startOrStop(Integer status, Long id) {
        //update employee set status = ? where id = ?

        //创建一个employee对象--修改状态本质上是修改employee表中的一个字段的属性值

        /*使用new关键字创建对象
        Employee employee = new Employee();
        employee.setStatus(status);
        employee.setId(id);
        */

        //使用构造器构造对象--需要在实体类上加@Builder注解
        Employee employee = Employee.builder()
                .status(status)
                .id(id)
                .build();

        //调用Mapper的update方法执行sql语句
        employeeMapper.update(employee);
    }

    //根据id查询员工
    @Override
    public Employee getById(Long id) {
        //select * from employee where id = ?
        Employee employee = employeeMapper.selectById(id);
        employee.setPassword("******");
        return employee;
    }

    //编辑员工信息
    @Override
    public void update(EmployeeDTO employeeDTO) {
        //1.将DTO对象转成实体对象-对象属性拷贝-对象拷贝工具类BeanUtils
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);

        //2.补充基础属性-设置修改时间和修改人---使用@AutoFill注解集成了
        /*
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());
        */

        //3.调用Mapper操作数据库
        employeeMapper.update(employee);
    }

    //修改密码
    @Override
    public void editPassword(PasswordEditDTO passwordEditDTO) {
        Long empId = BaseContext.getCurrentId();
        String oldPassword = passwordEditDTO.getOldPassword();
        String newPassword = passwordEditDTO.getNewPassword();
        //1.查询员工信息
        Employee employee = employeeMapper.selectById(empId);
        if (employee == null){
            throw new BaseException("用户不存在");
        }
        //2.验证旧密码
        String oldPwd = DigestUtils.md5DigestAsHex(oldPassword.getBytes());
        if (!oldPwd.equals(employee.getPassword())){
            throw new BaseException("旧密码错误");
        }
        //3.新密码不能与旧密码相同
        String newPwd = DigestUtils.md5DigestAsHex(newPassword.getBytes());
        if (newPwd.equals(employee.getPassword())){
            throw new BaseException("新密码不能与旧密码相同");
        }
        //4.更新新密码
        Employee updateEmployee = new Employee();
        updateEmployee.setId(BaseContext.getCurrentId());
        updateEmployee.setPassword(newPwd);
        //updateEmployee.setUpdateTime(LocalDateTime.now());

        employeeMapper.update(updateEmployee);
    }
}